package servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.sql.Connection;
import java.util.Scanner;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import SqlJavaBean.MakeTestBean;
import t.DBBean;
import t.makeTest;

/**
 * Servlet implementation class makePractise
 */
@WebServlet("/makePractise.view")
@MultipartConfig()
public class makePractise extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public makePractise() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");
		
		Part p1 = request.getPart("subjectFile");
		Part p2 = request.getPart("sqlFile");
		String partName = request.getParameter("partName");
		String endTime = request.getParameter("endTime");
		String subjectData = getData(p1);
		String sqlData = getData(p2);
		HttpSession s = request.getSession();
		Connection con = (Connection)s.getAttribute("con");
		if(con==null){
			return;
		}
		MakeTestBean make = new MakeTestBean(con);
		String f1 = make.createPractise(partName, endTime);
		String f2 = make.addPractiseData(partName, subjectData);
		String f3 = make.createEnvironment(sqlData);
		if(!f1.equals("OK")) request.setAttribute("callback","fail('发题失败!已存在同名练习,请更改练习名称')");
		else if(!f2.equals("OK"))request.setAttribute("callback","fail('添加题目失败！请检查题目格式')");
		else if(!f3.equals("OK"))request.setAttribute("callback","fail('创建试题环境失败!请检查.SQL文件格式，必须符合MySql语法')");
		else request.setAttribute("callback","success()");
		request.getRequestDispatcher("makePartPractise.jsp").forward(request, response);	
	}
	
	private String getData(Part p){
		String res = "";
		try{
			InputStream s = p.getInputStream();
			Scanner sc = new Scanner(s);
			while(sc.hasNext()) res = res+sc.nextLine();
		}
		catch(Exception e){
			
		}
		return res;
	}
	

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
